package com.qk.management.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> listByCourse(String subject) {
        return courseMapper.selectList(Wrappers.lambdaQuery(Course.class)
                .eq(Course::getSubject, Integer.valueOf(subject)));
    }

    @Override
    public List<CourseDTO.Data> listAllCourses() {
        List<Course> courses = courseMapper.selectList(null);
        return courses.stream().map(course -> CourseDTO.Data.builder()
                .id(course.getId())
                .subject(course.getSubject())
                .name(course.getName())
                .price(course.getPrice())
                .target(course.getTarget())
                .description(course.getDescription())
                .createTime(course.getCreateTime())
                .updateTime(course.getUpdateTime())
                .build()).collect(Collectors.toList());
    }

    @Override
    public PageResult<Course> pageCourse(String name, Integer subject, Integer target, Integer page, Integer pageSize) {
        Integer total = courseMapper.count(name,subject,target);
        Integer offSet =(page-1)*pageSize;
        List<Course> rows = courseMapper.selectByPage(name,subject,target,offSet,pageSize);
        return PageResult.<Course>builder().total(total).rows(rows).build();
    }

    @Override
    public void deleteById(Integer id) {
        courseMapper.deleteById(id);
    }

    @Override
    public void add(Course course) {
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public Course findById(Integer id) {
        return courseMapper.findById(id);
    }

    @Override
    public void update(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.update(course);
    }


}
